package com.tanhua.dubbo.huanxin.service;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.tanhua.dubbo.huanxin.config.AliyunSMSCon;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class HuanXInSmsService {

    @Autowired
    private AliyunSMSCon aliyunSMSConfig;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public static final String REDIS_CODE = "CHECK_CODE_";

    /**
     * 发送短信
     *
     * @param mobile
     * @return
     */
    public String sendSms(String mobile) {

        //随机生成6位数字验证码
        String code = "验证码发送失败，请人工干预";

        SendSmsResponse sendSmsResponse;
        try {

            Config config = new Config()
                    // 您的AccessKey ID
                    .setAccessKeyId(this.aliyunSMSConfig.getAccessKeyId())
                    // 您的AccessKey Secret
                    .setAccessKeySecret(this.aliyunSMSConfig.getAccessKeySecret())
                    .setEndpoint(this.aliyunSMSConfig.getDomain());
            // 访问的域名
            Client client = new Client(config);

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile) //目标手机号
                    .setSignName(this.aliyunSMSConfig.getSignName()) //签名名称
                    .setTemplateCode(this.aliyunSMSConfig.getTemplateCode()) //短信模板code
                    .setTemplateParam("{\"code\":\"" + code + "\"}"); //模板中变量替换
            //发送请求
            sendSmsResponse = client.sendSms(sendSmsRequest);

            if (StrUtil.equals(sendSmsResponse.getBody().getCode(), "OK")) {
                //发送成功
                return code;
            }
        } catch (Exception e) {
            log.error("发送短信验证码失败！mobile = {}", mobile, e);
        }
        return null;
    }
}
